package com.tv.task.app.tauri.api.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tv.task.app.tauri.api.module.domain.dto.TaskDTO;
import com.tv.task.app.tauri.api.module.domain.entity.Task;
import com.tv.task.app.tauri.api.module.service.TaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author elcker
 * @title TaskController
 * @date 2025/2/6 9:51
 * @description crud
 */
@RestController
@RequestMapping("/task")
public class TaskController {
    @Qualifier("taskServiceImpl")
    @Autowired
    private TaskService task;

    @PostMapping("addTask")
    public boolean addTask(@RequestBody TaskDTO taskDTO) {
        Task task = new Task();
        BeanUtils.copyProperties(taskDTO, task);
        task.setTime(new Date());
        return this.task.save(task);
    }

    @PatchMapping("updateTask")
    public boolean updateTask(@RequestBody TaskDTO taskDTO) {
        Task task = this.task.getById(taskDTO.getId());
        if (task == null) {
            return false;
        }
        task.setState(taskDTO.getState());
        return this.task.updateById(task);
    }

    @GetMapping("queryTask")
    public List<TaskDTO> queryTask(@ModelAttribute TaskDTO ts) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(ts.getTitle()), "title", ts.getTitle());
        queryWrapper.orderByDesc("type,time,state");
        return task.list(queryWrapper).stream().map(item -> {
            TaskDTO taskDTO = new TaskDTO();
            BeanUtils.copyProperties(item, taskDTO);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = formatter.format(item.getTime());
            taskDTO.setTime(formattedDateTime);
            return taskDTO;
        }).toList();
    }
}
